<template>
  <div class="bg-white m-4 mr-0 overflow-hidden">
    <a-spin :spinning="loading">
      <a-select :fieldNames="projectFields" :options="projects" v-model:value="cntFltParams.wmProjectId" allow-clear placeholder="所有项目" class="w-full mb-3" @change="projectChange"></a-select>
      <a-select :fieldNames="buFields" :options="buList" v-model:value="prodFltParams.buId" :allow-clear="props.showAll" placeholder="所有部门" class="w-full mb-3" @change="buChange"></a-select>
      <a-input-search placeholder="按合同名搜索…" style="margin-bottom: 10px" @search="onSearch" />
      <a-tree
        v-if="!treeReloading"
        title="产品列表"
        toolbar
        showLine
        :clickRowToExpand="false"
        :treeData="treeData"
        :load-data="loadProductTreeData"
        :selectedKeys="selectedKeys"
        v-model:expandedKeys="expandedKeys"
        show-icon
        @select="onSelect">
        <template #title="{ key,name,title,code, isContract }">
          <div v-if="isContract" @dblclick.prevent="handleContrackdbClick(key)">
            <a-tooltip placement="rightTop" title="双击查看合同详情">
              <span><a-tag class="mr-1" color="blue" @click.prevent="handleContractClick(key)">合同</a-tag>{{ name }}</span>
              <div><span class="font-size-3 color-gray">{{code}}</span></div>
            </a-tooltip>
          </div>
          <span v-else>{{title}}</span>
        </template>

      </a-tree>
    </a-spin>
    <WmContractModal @register="regContractModal"></WmContractModal>
  </div>
</template>

<script lang="ts" setup>
  import {nextTick, reactive, ref} from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { list,buBindList,loadContractDeptTree } from '../WmContract.api';
  import {userBuList} from '/@/views/system/depart/depart.api'
  import {filter} from '/@/utils/helper/treeHelper'
  import { useUserStore } from '/@/store/modules/user';
  import {detail as contractDetail} from "@/views/wmhb/contract/WmContract.api";
  import WmContractModal from "@/views/wmhb/contract/components/WmContractModal.vue";
  import {useModal} from "@/components/Modal";
  import {list as ProjectList} from "@/views/wmhb/project/WmProject.api";

  const [regContractModal,{openModal:openContractModal}] = useModal()
  const userStore = useUserStore();
  const emit = defineEmits(['select','onceClick','doubleClick']);
  const props = defineProps({
    projectDefault:{type:Boolean,default:false},
    buDefault:{type:Boolean,default:false},
    showAll:{ type: Boolean, default: false }
  })
  const { createMessage } = useMessage();

  let loading = ref<boolean>(false);
  // 部门树列表数据
  let treeData = ref<any[]>([]);
  // 当前展开的项
  let expandedKeys = ref<any[]>([]);
  // 当前选中的项
  let selectedKeys = ref<any[]>([]);
  const currentProduct = ref<any>(null);
  // 树组件重新加载
  let treeReloading = ref<boolean>(false);
  const projectFields = ref({
    label:'name',
    value:'id'
  })
  const buFields = ref({
    label:'departName',
    value:'id'
  })
  const cntFltParams = reactive({pageNo:1,pageSize:99999,name:'',wmProjectId:null})
  const prodFltParams = reactive({buId:null,wmContractId:''})
  const buList = ref<Recordable>([])
  const projects = ref<Recordable>([])

  const searchKeyword = ref('');

  treeInit()

  async function loadprojectList() {
    const result = await ProjectList({pageNo:1,pageSize:99999,status:'CONFIRMED'});
    if (!result || result.records.length == 0) {
      return;
    }
    if (props.projectDefault){
      cntFltParams.wmProjectId=result.records[0].id
    }
    projects.value = result.records
  }

  async function buDepartList(){
      const result = await userBuList({isBu:'Y'})
      if (Array.isArray(result)){
          buList.value = result
          if (props.buDefault){
            prodFltParams.buId = result[0].id
          }
        }
    }


  async function loadContracList(){
    loading.value = true
    const result = await list(cntFltParams)
    let rootData = []
    if (result.records&&result.records.length){
      rootData = result.records.map(record=> {
        return {
          ...record,
          key:record.id,
          isContract:true,
          code:record.code,
          isLeaf:false,
          parentId:"",
          title:record.name,
          children:[]
        }
      })
    }
    treeData.value = rootData;
    if (expandedKeys.value.length === 0) {
        autoExpandParentNode();
      } else {
        if (selectedKeys.value.length === 0) {
          let item = treeData.value[0];
          if (item) {
            // 默认选中第一个
            setSelectedKey(item.id, item);
          }
        } else {
          emit('select', currentProduct.value);
        }
      }
    loading.value=false
  }

  async function loadProductTreeData(treeNode) {
    if (!treeNode.dataRef.code){
      return Promise.resolve()
    }
    try {
      const params = {'async': false,'pcode':'',wmContractId:treeNode.dataRef.id}
      const result = await loadContractDeptTree(params)
      prodFltParams.wmContractId = treeNode.dataRef.id
      const bindList = await buBindList(prodFltParams)
      const filteredRes = treeDataFilter(result, bindList)
      if (filteredRes.length == 0) {
        treeNode.dataRef.isLeaf = true;
      } else {
        treeNode.dataRef.children = filteredRes;
        // if (expandedKeys.value.length > 0) {
        //   let subKeys: any[] = [];
        //   for (let key of expandedKeys.value) {
        //     if (filteredRes.findIndex((item) => item.key === key) !== -1) {
        //       subKeys.push(key);
        //     }
        //   }
        //   if (subKeys.length > 0) {
        //     debugger
        //     expandedKeys.value = [...expandedKeys.value];
        //   }
        // }
      }
      treeData.value = [...treeData.value];
    }catch (e){
      console.log(e)
    }
    return Promise.resolve()
  }



  async function treeInit(){
    await loadprojectList()
    await buDepartList()
    await loadContracList();
  }

  // 自动展开父节点，只展开一级
  function autoExpandParentNode() {
    if (!treeData.value.length)
      return
    let item = treeData.value[0];
    if (item) {
      if (!item.isLeaf) {
        expandedKeys.value = [item.key];
      }
      // 默认选中第一个
      setSelectedKey(item.id, item);
      reloadTree();
    } else {
      emit('select', null,prodFltParams.buId);
    }
  }

  // 重新加载树组件，防止无法默认展开数据
  async function reloadTree() {
    await nextTick();
    treeReloading.value = true;
    await nextTick();
    treeReloading.value = false;
  }

  function treeDataFilter(treeData,fltKeys){
    if (!treeData.length)
      return []
    if (!fltKeys.length)
      return []
    return  filter(treeData,(node)=>{
      return fltKeys.includes(node.key)
      },
      {id: 'key', children: 'children', pid: 'parentId',})
  }

  /**
   * 设置当前选中的行
   */
  function setSelectedKey(key: string, data?: object) {
    selectedKeys.value = [key];
    if (data) {
      currentProduct.value = data
      emit('select', data,prodFltParams.buId);
    }
  }

  // 树选择事件
  function onSelect(selKeys, event) {
    if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
      setSelectedKey(selKeys[0], event.selectedNodes[0]);
    } else {
      // 这样可以防止用户取消选择
      setSelectedKey(selectedKeys.value[0]);
    }
  }

  async function onSearch(value: string) {
    if (value) {
      cntFltParams.name=value
    } else {
      cntFltParams.name=''
    }
    await buChange(prodFltParams.buId)
    searchKeyword.value = value;
  }

  function handleContractClick(contractId){
    emit('onceClick',contractId)
  }

  async function handleContrackdbClick(contractId){
    const result = await contractDetail({id:contractId})
    openContractModal(true,{
      record:result,
      isUpdate: true,
      showFooter: false,
    })
    emit('doubleClick',contractId)
  }

  async function buChange(val){
    expandedKeys.value=[]
    selectedKeys.value=[]
    currentProduct.value=null
    prodFltParams.buId = val
    await loadContracList()
  }
  async function projectChange(val){
    expandedKeys.value=[]
    selectedKeys.value=[]
    currentProduct.value=null
    cntFltParams.wmProjectId=val
    await loadContracList()
  }

</script>
<style lang="less" scoped>
  /*升级antd3后，查询框与树贴的太近，样式优化*/
  :deep(.jeecg-tree-header) {
    margin-bottom: 6px;
  }
</style>
